package com.nit.lab.vote.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class UploadFileUtil {
    private static final String SERVER_NAME = "/file";
    private static final String URL_HEAD = "..";
    private static final String PATH_HEAD = "/home/lab207/vote-client/";

    //获取流文件
    private static void inputStreamToFile(InputStream ins, FileOutputStream os) throws IOException {
        int bytesRead = 0;
        int len = 10 * 1024 * 1024;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
    }

    /**
     * 上传文件到服务器的指定路径
     *
     * @return 文件最终地址
     */
    public static String uploadFile(MultipartFile multipartFile, String relativePath) throws IOException {
        File file;
        String url = null;
        if (multipartFile != null) {
            String fileName = multipartFile.getOriginalFilename();
            String path = SERVER_NAME + relativePath;
            InputStream is = multipartFile.getInputStream();
            if (fileName != null) {
                url = path + "/" + fileName;
                file = new File("../vote-client" + path);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File existFile = new File("../vote-client" + url);
                if (existFile.exists()) {
                    return null;
                }
                inputStreamToFile(is, new FileOutputStream("../vote-client" + url));
                is.close();
            }
        }
        return ".." + url;
    }

    /**
     * 删除本地临时文件
     */
    public static void deleteTempFile(String fileURL) throws NullPointerException {
        if (fileURL != null) {
            if (fileURL.startsWith(URL_HEAD)) {
                fileURL = PATH_HEAD + fileURL.substring(URL_HEAD.length() + 1);
            }
            File file = new File(fileURL);
            file.delete();
        } else {
            throw new NullPointerException();
        }
    }

    public static void main(String[] args) throws Exception {
//        deleteTempFile("http://127.0.0.1:8555/file/小a1-1-11/1/1.txt");
    }
}
